/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Friend;
import edu.cmu.fithub.db.bean.User;

public class SearchFriendAction extends Action {

	public SearchFriendAction() {
	}

	public String getName() {
		return "searchFriend.do";
	}

	public String perform(HttpServletRequest request) {

		User user = (User) request.getSession().getAttribute("user");
		String searchUser = request.getParameter("search_person");
		Session dbSession = DBHelper.getSessionFactory().openSession();
		List<Friend> friendList = dbSession.createCriteria(Friend.class)
				.setFetchMode("User", FetchMode.JOIN).list();
		List<User> list = dbSession.createCriteria(User.class)
				.add(Restrictions.ilike("firstName", "%" + searchUser + "%"))
				.add(Restrictions.ne("userId", user.getUserId())).list();
		List<Integer> friendIdList = new ArrayList<Integer>();
		for (int i = 0; i < friendList.size(); i++) {
			friendIdList.add(friendList.get(i).getFriendId());
		}
/*
		System.out.println("before list.size = " + list.size());
		for (int i = 0; i < list.size(); i++) {
			if (friendIdList.contains(list.get(i).getUserId())) {
				System.out
						.println("removing user " + list.get(i).getUsername());
				list.remove(i);
			}
		}
		System.out.println("after list.size = " + list.size());
*/
		User[] userList = new User[list.size()];
		userList = (User[]) list.toArray(userList);
		request.setAttribute("userList", userList);
		return "displayFriends.do";
	}
}
